(function($) {
var photoTag = {   
    show: function(left,top,width, height, show_resize_square) {
        $('#select-area-box').css({'left':left - 7, 'top':top - 7})
        $('#select-area-box').width(width + 4).height(height + 4).show();
        $('#select-area').width(width).height(height);
        if(show_resize_square) $('#select-area-box span').show();
        else $('#select-area-box span').hide();
    },
    hide: function() {$('#select-area-box').hide();    },
    add:function(tag_name, left, top, width, height) {
        var json = {id:Math.floor(Math.random() * 10000)};
        //$.getJSON('add_tag.php', {'name':tag_name,'left':left,'top':top,'width':width,'height':height}, function(json) {
            //reflesh tag list
        //    if(json.message) alert(json.message);
        //    if(json.error == 0) {
                var args = left+','+top+','+width+','+height;
                var li = '<li>,';
                li += '<span onmouseover="photoTag.show('+args+');" ';
                li += 'onmouseout="photoTag.hide();">'+tag_name+'</span>';
                li += '(<a href="javascript:;" onclick="photoTag.remove('+json.id+',this.parentNode);" ';
                li += 'onmouseover="photoTag.show('+args+');" onmouseout="photoTag.hide();">删除</a>)';
                li += '</li>';
                $('#tag-list').append(li);                
        //    }
        //});
    },
    remove: function(id, li) {
        //$.getJSON('remove_tag.php', {'tag_id':id}, function(json) {
            //reflesh tag list
        //    if(json.message) alert(json.message);
        //    if(json.error == 0) 
                li.parentNode.removeChild(li);
        //});
    }
};

function startQQ() {
    var is_started = false;
    // 选区左上角,和高宽
    var info = {'left':0,'top':0,'width':0,'height':0};
    var origin = {x:$('#enclose-wrapper').offset().left + (parseInt($('#enclose-wrapper').css('border-left-width'))||0),
                  y:$('#enclose-wrapper').offset().top  + (parseInt($('#enclose-wrapper').css('border-top-width'))||0)};
    var dnr = new DragResize($('#select-area-box')[0], {
        minWidth:20,
        minHeight:20,
        bound:{left:0,top:0,right:9999,bottom:9999},
        callback:function(i) {
            // 7为左(上)边两个边框的宽度的和, 4为左右(上下)篮色边框宽度的和
            info= {'left':i.left + 7,'top':i.top + 7,'width':i.width - 4,'height':i.height - 4};
            $('#select-area').width(info.width).height(info.height);
            // 将添加标签的表单定位在选区的右边
            $('#form-add-tag').css({'left':i.left + i.width + 10, 'top':i.top});
        }                
    });
    // 拖动选区
    $('#select-area').mousedown(function(e){
        dnr.drag(e);
    });
    // 调整选区大小
    $('#select-area-box span').mousedown(function(e){
        dnr.resize(e, this.className.replace('-resize', ''));
    });
    // 在图片上点击一下,开始获取选区
    $('#photo').mousedown(function(e){
        if(is_started) return;
        is_started = true;
        var left = e.pageX - origin.x - 50 - 7;
        var top  = e.pageY - origin.y - 50 - 7 ;

        info= {'left':left + 7,'top':top + 7,'width':100,'height':100};
        photoTag.show(info.left, info.top, info.width, info.height, true);
        $('#form-add-tag').show().css({'left':left + 100 + 4 + 10, 'top':top});
    });
    // 鼠标进入图片内时,显示选区
    $('#photo').bind('mouseenter',function(e){
        if(!is_started) return;
        photoTag.show(info.left, info.top, info.width, info.height, true);
    });
    // 确定添加一个标签,或取消
    $('#btn-add-tag, #btn-cancel').click(function(e){
        if(this.id == 'btn-cancel') {
            $('#form-add-tag, #select-area-box').hide();
            is_started = false;
            return false;
        }
        if(!$('#tag-name').val()) {
            alert('标签名不能为空！');
            return false;
        }
        // 添加标签
        photoTag.add($('#tag-name').val(), info.left, info.top, info.width, info.height);
        // 隐藏选区和表单
        $('#form-add-tag, #select-area-box').hide();
        is_started = false;
    });
    photoTag.hide();
}

Douban = new Object();
Douban.errdetail = [
    '','未知错误','文件过大',
    '信息不全','域名错误','分类错误',
    '用户错误','权限不足','没有文件',
    '保存文件错误','不支持的文件格式','超时',
    '文件格式有误','','添加文件出错',
    '已经达到容量上限','不存在的相册','删除失败']

Douban.EventMonitor = function(){
    this.listeners = new Object();
}

Douban.EventMonitor.prototype.broadcast=function(widgetObj, msg, data){
    var lst = this.listeners[msg];
    if(lst != null){
        for(var o in lst){
            lst[o](widgetObj, data);
        }
    }
}
Douban.EventMonitor.prototype.subscribe=function(msg, callback){
    var lst = this.listeners[msg];
    if (lst) {
        lst.push(callback);
    } else {
        this.listeners[msg] = [callback];
    }
}
Douban.EventMonitor.prototype.unsubscribe=function(msg, callback){
    var lst = this.listener[msg];
    if (lst != null){
        lst = lst.filter(function(ele, index, arr){return ele!=callback;});
    }
}

// Page scope event-monitor obj.
var event_monitor = new Douban.EventMonitor();

$.viewport_size = function(){
	var size = [0, 0];
	if (typeof window.innerWidth != 'undefined'){
		size = [window.innerWidth, window.innerHeight];
	}else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0){
		size = [document.documentElement.clientWidth, document.documentElement.clientHeight];
	}else{
		size = [document.body.clientWidth, document.body.clientHeight];
	}
	return size;
}


function load_event_monitor(root) {
    var re = /a_(\w+)/;
    var fns = {};
    $("#j", root).each(function(i) {
        var m = re.exec(this.className);
        if (m) {
            var f = fns[m[1]];
            if (!f) {
                f = eval("Douban.init_"+m[1]);
                fns[m[1]] = f;
            }
            f && f(this);
        }
    });
    $(".j", root).each(function(i) {
        var m = re.exec(this.className);
        if (m) {
            var f = fns[m[1]];
            if (!f) {
                f = eval("Douban.init_"+m[1]);
                fns[m[1]] = f;
            }
            f && f(this);
        }
    });
}

$(function() {
    load_event_monitor(document);
});

Douban.prettify_form = function(form) {
    $('input:submit', form).each(function(i) {
        var btn = $('<a href="#" class="butt"></a>').text($(this).val());
        btn.click(function() {
            cleanTip();
            form.submit();
            return false;
        });
        $(this).hide().after(btn);
    });
}

var get_form_fields = function(form) {
    var param = {};
    $(':input', form).each(function(i){
        var name = this.name;
        if (this.type == 'radio') {
            if (this.checked) param[name] = this.value;
        } else if (this.type == 'checkbox') {
            if (this.checked) param[name] = this.value;
        } else if (this.type == 'submit'){
            if (/selected/.test(this.className)) param[name] = this.value;
        } else {
            if (name) param[name] = this.value;
        }
        if(/notnull/.test(this.className) && this.value == ''){
            $(this).prev().addClass('errnotnull');
            param['err'] = 'notnull';
        }
    });
    return param;
}

var remote_submit_json = function(form, func, disable, action) {
    var fvalue = get_form_fields(form);
    if(fvalue['err'] != undefined) return;
    $(':submit,:input',form).attr('disabled',disable==false?0:1);
    var act = action || form.action;
    $.post_withck(act, fvalue, function(ret){
        var json = eval('('+ret+')'); func(json);
    });
}

Douban.init_login_form = function(form) {
  $(form).submit(function() {
		remote_submit_json(this, function(data){
      if (!data['err']) {
            show_dialog(null);
            var url = data['refer']; 
            $.getJSON(url,  function(r) {
              if($('#dialog').length){
                $('#dialog').html(r.html);
                refine_dialog();
                load_event_monitor($('#dialog'));
              }
            });
               
      } else {
        $(':submit,:input',form).attr('disabled',0);
        alert(data['err']);
        //$('#notice .text').text(data['err']);
      }
  	}, false);
    return false;
	});
}

Douban.init_update_pic = function(form) {
  $(form).submit(function() {
		remote_submit_json(this, function(data){
      if (!data['err']) {
        $('#space_avatar img').attr('src', data['pic']);
        $('#pic_form').hide();
        pick = 0;
      } else {
        $(':submit,:input',form).attr('disabled',0);
        alert(data['err']);
        //$('#notice .text').text(data['err']);
      }
  	}, false);
    return false;
	});
}

Douban.init_update_spotnote = function(form) {
  $(form).submit(function() {
		remote_submit_json(this, function(data){
      if (!data['err']) {
        $('.article').html(data['announcement']);
        $('#announce_form').hide();
        tick = 0;
      } else {
        $(':submit,:input',form).attr('disabled',0);
        alert(data['err']);
        //$('#notice .text').text(data['err']);
      }
  	}, false);
    return false;
	});
}

Douban.init_update_announce = function(form) {
  $(form).submit(function() {
		remote_submit_json(this, function(data){
      if (!data['err']) {
        $('#article').html(data['announcement']);
        $('#announce_form').hide();
        tick = 0;
      } else {
        $(':submit,:input',form).attr('disabled',0);
        alert(data['err']);
        //$('#notice .text').text(data['err']);
      }
  	}, false);
    return false;
	});
}

Douban.init_update_pic_title = function(form) {
  $(form).submit(function() {
		remote_submit_json(this, function(data){
      if (!data['err']) {
        $('.pic_title').html(data['pic_title']);
        $('#title_form').hide();
        tick = 0;
      } else {
        $(':submit,:input',form).attr('disabled',0);
        alert(data['err']);
        //$('#notice .text').text(data['err']);
      }
  	}, false);
    return false;
	});
}
Douban.init_profile_form = function(form) {
	$(form).submit(function() {
		remote_submit_json(this, function(data){
      if (!data['err']) {
          if (!data['spotreferred']) { // basic logic
            window.location.href = 'site.php?ac=profile&profid='+data['profid']; 
            close_dialog();
          } else if (data['picreferred']) {
            window.location.reload();
            //window.location.href = window.location.href;
            close_dialog();
          } else { // to goto create spot 
            if($('#dialog').length){
                setTimeout(function() {
                $('#dialog').html(data['html']);
                refine_dialog();
                load_event_monitor($('#dialog'));
                }, 200);
            }
          }
      } else {
          $(':submit,:input',form).attr('disabled',0);
          alert(data['err']);
          //$('#notice .text').text(data['err']);
      }
  	});
    return false;
	});
	//$(form.cancel).click(function(){
	//});
}

Douban.init_postpicprof_form = function(form) {
	$(form).submit(function() {
		remote_submit_json(this, function(data){
      if (!data['err']) {
        window.location.reload();
        //window.location.href = window.location.href; 
        close_dialog();
      } else {
          if (data['step'] == 1) {
            if($('#dialog').length) {
                setTimeout(function() {
                    $('#dialog').html(data['html']);
                    refine_dialog();
                    load_event_monitor($('#dialog'));
                }, 200);
            }
          } else {
            $(':submit,:input',form).attr('disabled',0);
            alert(data['err']);
          }
      }
  	});
    return false;
	});
	//$(form.cancel).click(function(){
	//});
}

Douban.init_interest_form = function(form) {
	$(form).submit(function() {
		remote_submit_json(this, function(data){
//      alert(data['err'] + data['spotid']);
      if (!data['err']) {
        window.location.href = 'site.php?ac=image&type=spot&id='+data['spotid']; 
        close_dialog();
      } else {
          if (data['step'] == 1) {
            if($('#dialog').length) {
                setTimeout(function() {
                    $('#dialog').html(data['html']);
                    refine_dialog();
                    load_event_monitor($('#dialog'));
                }, 200);
            }
          } else {
            $(':submit,:input',form).attr('disabled',0);
            alert(data['err']);
          }
      }
  	});
    return false;
	});
	//$(form.cancel).click(function(){
	//});
}

Douban.init_close_dialog = function(o) {
  $(o).click(function(){
    close_dialog();
  });
}

Douban.init_new_profile = function(o) {
    $(o).click(function(){
        if($('#hiddendialog').length){
            show_dialog($('#hiddendialog').html());
            load_event_monitor($('#dialog'));
        }else{
            show_dialog(null);
            var _ = $(this).attr('name').split('-');
            var type = _[0], fid = _[1];            
            var url = 'site.php?ac=profile&op=new&fid='+fid;
            //alert(url);
            $.getJSON(url,  function(r) {
              if($('#dialog').length){
                $('#dialog').html(r.html);
                refine_dialog();
                load_event_monitor($('#dialog'));
              }
            });
        }
        return false;
   });
}

Douban.init_updone_form = function(form) {
	var picupload = new Ajax_upload('#button2', {
		action: 'site.php?ac=ajax&op=uppic', // I disabled uploads in this example for security reaaons
		autoSubmit: false,
    responseType: 'json',
    onSubmit : function(file , ext){
			//if (ext && new RegExp('^(' + allowed.join('|') + ')$').test(ext)){
			if (ext && /^(jpg|png|jpeg|gif)$/.test(ext)){
				/* Setting data */
				this.setData(
          get_form_fields(form)
        );
			} else {
				$('#example2 .text').text('请选择正确的文件类型， 我们支持jpg/png/gif格式的图片');
				// cancel upload
				return false;				
			}
	
		},
		onComplete : function(file, response){
        if(!response['err']) {
          if (response['type'] == 'spotid') {
            window.location.href = 'site.php?ac=image&type=spot&id='+response['id'];  
            close_dialog(); 
          } else {
            window.location.href = 'site.php?ac=image&type=profile&id='+response['id'];  
            close_dialog(); 
          }
        } else {
          alert(response['err']);
          $('#example2 .text').text(response['err']);				
        }
    },
    onChange : function(file, ext){
      $('#picfile').val(file);
    }
	});
  $(form).submit(function() {
    picupload.submit(); 
    return false;
	});
}

Douban.init_browse_pic = function(o) {
  $(o).select(function(){
     alert($(o).value); 
  });
  $(o).click(function(){
    // alert($(o).value); 
  });
}



Douban.init_spot_pic_qq = function(o) {
  $(o).click(function(){
      startQQ();  
  });
}

Douban.init_addprof_onpic = function(o) {
    $(o).click(function(){
        if($('#hiddendialog').length){
            show_dialog($('#hiddendialog').html());
            load_event_monitor($('#dialog'));
        }else{
            show_dialog(null);
            var _ = $(this).attr('name').split('-');
            var id = _[0], p = _[1];            
            var url = 'site.php?ac=image&op=add&type=profile&id=' + id + '&picid=' + p;
            $.getJSON(url,  function(r) {
              if($('#dialog').length){
                $('#dialog').html(r.html);
                refine_dialog();
                load_event_monitor($('#dialog'));
              }
            });
        }
        return false;
    });
}
Douban.init_addspot_btn = function(o) {
    $(o).click(function(){
        if($('#hiddendialog').length){
            show_dialog($('#hiddendialog').html());
            load_event_monitor($('#dialog'));
        }else{
            show_dialog(null);
            var url = 'site.php?ac=spot&op=new&profid=' + $(this).attr('name');
            $.getJSON(url,  function(r) {
              if($('#dialog').length){
                $('#dialog').html(r.html);
                refine_dialog();
                load_event_monitor($('#dialog'));
              }
            });
        }
        return false;
    });
}

Douban.init_upload_btn = function(o) {
    $(o).click(function(){
        if($('#hiddendialog').length){
            show_dialog($('#hiddendialog').html());
            load_event_monitor($('#dialog'));
        }else{
            show_dialog(null);
            var _ = $(this).attr('name').split('-');
            var type = _[0], id = _[1];            
            var url = 'site.php?ac=ajax&op=upload&'+type+'='+id;
            $.getJSON(url,  function(r) {
              if($('#dialog').length){
                $('#dialog').html(r.html);
                refine_dialog();
                load_event_monitor($('#dialog'));
              }
            });
        }
        return false;
    });

}


Douban.init_show_login = function(o){
    $(o).click(function(){
        return pop_win.load('/js/pop_win/login')
    });
}

Douban.init_show_signup_table = function(o){
    $(o).click(function(){
		event_id = window.location.href.split('/')[4];
        return pop_win.load('/j/event/'+event_id+'/signup')
    });
}

var set_cookie = function(dict, days){
    days = days || 30;
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
    for (var i in dict){
        document.cookie = i+"="+dict[i]+expires+"; path=/";
    }
}

function get_cookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) {
            return c.substring(nameEQ.length,c.length).replace(/\"/g,'');
        }
    }
    return null;
}

Douban.init_hideme = function(o){
    $(o).click(function(){
        $(this).parent().parent().parent().hide();
    });
}

Douban.init_more = function(o){
    $(o).click(function(){
        lastObj = $(this).prev().find("input");
        ids = /(.*_)(\d+)$/.exec( lastObj.attr("id"));
        id = ids[1] + (parseInt(ids[2]) + 1);
        a = lastObj.clone();
        a.attr("value","");
        $(this).before('<br/>').before(a);
        a.attr('id',id).attr('name',id).wrap('<span></span>');
    })
}

Douban.init_search_text = function(o){
    if(!o.value || o.value == o.title){
        $(o).addClass("greyinput");
        o.value = o.title;
    }
    $(o).focus(function(){
        $(o).removeClass("greyinput");
        if(o.value == o.title) o.value = "";
    });
    $(o).blur(function(){
        if(!o.value){
            $(o).addClass("greyinput");
            o.value = o.title;
        }
    });
}

Douban.init_checkreg = function(o){
    $(o).find('.butt').click(function(){
        var check = true;
        $(o).find('input').each(function(){
            if(this.type!='submit' && this.type!='button'){
                if(this.value == ''){
                    $(this).next().css('display','inline');
                    check = false;
                }else{
                    $(this).next().css('display','none');
                }
            }
        });
        return check;
    });
}

Douban.init_click_tip = function(o){
    var tip = $(o).next('.blocktip');
    $(o).click(function(){
        tip.show().blur_hide();
        m = tip.width() + tip.pos().x - $.viewport_size()[0] > 0?
            -tip.width() : 0;
        tip.css('margin-left', m);
    })
    $('.hideme',tip).click(function(){ tip.hide(); })
}

function cleanTip(){
    if($("#page_focus")[0].title == $("#page_focus")[0].value){
        $("#page_focus")[0].value = '';
    }
}

Douban.init_submit_link = function(o){
	$(o).click(function(){
		$(o).parent().submit();
	});
}

var nowmenu = null;
var hidemenu = function(a){
	a.find('.down').css('display','inline');
	a.find('.up').hide();
	a.next().hide();
	nowmenu = null;
	$('body').unbind('mousedown');
}

var openmenu = function(a){
	if(nowmenu != null){
		hidemenu(nowmenu);
	}
	a.find('.up').css('display','inline');
	a.find('.down').hide();
	a.next().show();
	nowmenu = a;
	$('body').mousedown(function(){
		if(a.parent().attr('rel') != 'on'){
			hidemenu(a);
		}
	});
}

$(function(){
    $('#page_focus').suggest('site.php?ac=ajax&op=srh_prof',{
      formatItem: function(item) {
        return item.tagname;
      }
    })    
})

var show_dialog = function(div) {
    if($('#dialog').length) return;
    $('body').prepend('<div id="overlay"></div><div id="dialog"></div>');
    if(div != null){
        $('#dialog').html(div);
    }else{
        $('#dialog').html("<div class='loadpop'>正在载入，请稍候...</div>");
    }
    set_overlay();
}

var set_overlay = function(){
    var oheight = ($.browser.msie?11:26),
        dialog=$('#dialog')[0],
        w=dialog.offsetWidth,
        left=(document.body.offsetWidth-w)/2+'px';

    $('#overlay').css({height:dialog.offsetHeight+oheight,width:w+26,left:left});
    dialog.style.left=left;
}

var close_dialog = function() {
    $('#overlay').unbind('click');
    $('#dialog,#overlay,.bgi').remove();
    if (typeof document.body.style.maxHeight == "undefined") {//if IE6
        $('body','html').css({height: 'auto', width: 'auto'});
        $('html').css('overflow', '');
    }
    document.onkeydown = '';
    return false;
}

var refine_dialog = function(){
    var agent = navigator.userAgent.toLowerCase();
    var top = 0.5 * ($.viewport_size()[1] - $('#dialog')[0].offsetHeight) + 140;
    $('#dialog,#overlay').css('top', top);
    set_overlay();
}

Douban.init_show_full = function(o){
    $(o).click(function(){
        $(o).parents('.short').hide();
        $(o).parents('.short').next().show();
    })
}

Douban.init_show_short = function(o){
    $(o).click(function(){
        $(o).parents('.all').hide();
        $(o).parents('.all').prev().show();
    })
}



Douban.init_rec_btn= function(o) {
    var _ = $(o).attr('name').split('-');
    var url = '/j/recommend';
    var rdialog = 'rdialog-' + _[1] + '-' + _[2];
    var uid;
    var f = function(){
        uid = ((_[1] == 'I')&&(_[2]==undefined)) ? $('input',$(o).parent())[0].value : _[2];
        rec = (_[3]==undefined) ? '':_[3]
        var fcs = function(type){
            if(type == 'I'){
                var s = $('.text','#dialog');
                if(s.length)
                {
                    if(s[0].value.length){s[1].focus();}
                    else{s[0].focus();}
                }
            }else{
                $('#dialog').find(':submit').focus();
            }
        }
        if($('#' + rdialog).length){
            show_dialog($('#' + rdialog).html());
            load_event_monitor('#dialog');
            fcs(_[1]);
        }else{
            $.getJSON(url, {type:_[1], uid:uid, rec:rec}, function(r){
                show_dialog(r.html);
                if(_[1]!='I'){
                    var rechtml = $('<div id="'+rdialog+'"></div>');
                    rechtml.html(r.html).appendTo('body').hide();
                }
                load_event_monitor('#dialog');
                fcs(_[1]);
            });
        }
        return false;
    }
    $(o).click(f);
    if(_[1] == 'I'){
        $(o).parent().parent().submit(f);
    }
}

Douban.init_rec_form = function(form) {
    form.onsubmit = function(){
        remote_submit_json(this, function(data){
            $('#dialog').html('<div class="loadpop m">推荐已提交</div>');
            set_overlay();
            $('#rec_url_text').attr('value','http://');
                setTimeout(function(){
                $('#dialog, #overlay').fadeOut(close_dialog);
                if($('input[name=type]',form).val() == "I"){
                    document.location.reload();
                }
            },400);
        });
        return false;
    }
    $(form).set_len_limit(140);
}

Douban.init_rec_reply = function(o){
    var _ = o.name.split('-');
    var url = '/j/rec_comment';
    if(!o.rev){
        $(o).attr('rev', 'unfold');
    }
    $(o).click(function(){
        if(o.rev != 'unfold'){
            $(o).parent().parent().next().remove();
            $(o).html($(o).attr('rev'));
            o.rev = 'unfold';
        }else if(o.rel!="polling"){
            o.rel="polling"
            $.getJSON(url, {rid: _[2], type: _[3], n:_[4], ni:_[5]}, function(r){
                $('<div class="recreplylst"></div>').insertAfter($(o).parent().parent()).html(r.html);
                load_event_monitor($(o).parent().parent().next());
                $(o).attr('rev', $(o).html()).text('隐藏回应');
                o.rel=""
            })
        }
        return false;
    })
}

Douban.init_reply_form = function(form){
    $(form).attr('action', $(form).attr('rev'));
    var n = $(form).attr('name');
    $(form).submit(function(){
        remote_submit_json(this, function(r){
            var replst = $(form).parent();
            $(replst).html(r.html);
            load_event_monitor(replst);
	    if (n=='n'){
	    var a = $('<span><a href="javascript:void(0)">添加回应</a></span>');
	    }
	    else
	    {
            var a = $('<span style="margin-left:53px"><a href="javascript:void(0)">添加回应</a></span>');
	    }
            $('form', replst).hide().after(a);
            a.click(function(){
                $(this).prev().show();
                $(this).remove();
            })
        });
        $(':submit',form).attr('disabled', 1);
        return false;
    })
    $(form).set_len_limit(140);
}

Douban.init_video_comment = function(form){
    $(form).submit(function(){
        remote_submit_json(this, function(r){
            var insert_point = $('#comments');
            $(insert_point).html(r.html);
            load_event_monitor(insert_point);
            $(':submit', form).attr('disabled', 0);
            $('textarea', form).attr('disabled', 0);
            $('textarea', form).attr('value', '');
        }, true, '/j/video/add_comment');
        return false;
    })
}

Douban.init_video_del_comment = function(o){
    var _ = $(o).attr('name').split('-');
    $(o).click(function(){
        var text = o.title;
        if(confirm("真的要"+text+"?") == true){
                $.postJSON_withck("/j/video/del_comment", {comment_id: _[1], video_id: _[2]}, function(r){
                    var insert_point = $('#c-'+_[1]);
                    $(insert_point).html("");
                });
            }
        return false;
    })
}

Douban.init_morerec = function(o){
    $(o).click(function(){
        var n = $(o).parent().next();
        if(n.is(':hidden')){ n.show()} else {n.next().show()}
        $(o).remove();
    })
}



$.ajax_withck = function(options){
    if(options.type=="POST")
        options.data=$.extend(options.data||{},{ck:get_cookie('ck')});
    return $.ajax(options)
}

$.postJSON_withck = function(url, data, callback){
    $.post_withck(url, data, callback, "json");
}

$.post_withck = function( url, data, callback, type ) {
    if ($.isFunction(data)) {
        callback = data;
        data = {};
    }
    return $.ajax({
        type: "POST",
        url: url,
        data: $.extend(data,{ck:get_cookie('ck')}),
        success: callback,
        dataType: type
    });
}

$.fn.extend({
    pos:function() {
        var o = this[0];
        if(o.offsetParent) {
            for(var posX=0, posY=0; o.offsetParent; o=o.offsetParent){
                posX += o.offsetLeft;
                posY += o.offsetTop;
            }
            return {x:posX, y:posY};
        } else return {x:o.x, y:o.y};
    },

    set_len_limit : function(limit){
        var s = this.find(':submit:first');
        var oldv = s.attr('value');
        var check = function(){
            if(this.value && this.value.length > limit){
                s.attr('disabled',1).attr('value','字数不能超过'+limit+'字');
            } else {
                s.attr('disabled',0).attr('value', oldv);
            }
        }
        $('textarea', this).focus(check).blur(check).keydown(check).keyup(check);
    },

    set_caret: function(){
        if(!$.browser.msie) return;
        var initSetCaret = function(){this.p = document.selection.createRange().duplicate()};
        this.click(initSetCaret).select(initSetCaret).keyup(initSetCaret);
    },

    insert_caret:function(t){
        var o = this[0];
        if(document.all && o.createTextRange && o.p){
            var p=o.p;
            p.text = p.text.charAt(p.text.length-1) == '' ? t+'' : t;
        } else if(o.setSelectionRange){
            var s=o.selectionStart;
            var e=o.selectionEnd;
            var t1=o.value.substring(0,s);
            var t2=o.value.substring(e);
            o.value=t1+t+t2;
            o.focus();
            var len=t.length;
            o.setSelectionRange(s+len,s+len);
            o.blur();
        } else {
            o.value+=t;
        }
    },

    get_sel:function(){
        var o = this[0];
        return document.all && o.createTextRange && o.p ?
            o.p.text : o.setSelectionRange ?
            o.value.substring(o.selectionStart,o.selectionEnd) : '';
    },
    blur_hide:function(){
        var s=this,h=function(){return false};
        s.mousedown(h)
        $().mousedown(function(){
            s.hide().unbind('mousedown',h)
            $().unbind('mousedown',arguments.callee);
        })
        return this;
    },
    yellow_fade:function() {
        var m = 0,setp=1,self=this;
        function _yellow_fade(){
            self.css({backgroundColor:"rgb(100%,100%,"+m+"%)"})
            m += setp;setp+=.5;
            if(m <= 100){
                setTimeout(_yellow_fade,35)
            }else{
                self.css({backgroundColor:""})
            }
        };
        _yellow_fade();
        return this;
    },
    hover_fold:function(type){
        var i = {folder:[1,3], unfolder:[0,2]}, s = function(o,n){
            return function(){$('img',o).attr("src","/pics/arrow"+n+".gif");}
        }
        return this.hover(s(this,i[type][0]),s(this,i[type][1]));
    }
})

var check_form = function(form){
    var _re = true;
    $(':input',form).each(function(){
        if((/notnull/.test(this.className) && this.value == '')
            || (/most/.test(this.className) && this.value && this.value.length>/most(\d*)/.exec(this.className)[1]))
        {
            $(this).next().show();
            _re = false;
        }else{
            if(/attn/.test($(this).next().attr('className'))) $(this).next().hide();
        }
    })
    return _re;
}

var paras = function(s){
    var o = {};
    if(s.indexOf('?') == -1) return {};
    var vs = s.split('?')[1].split('&');
    for(var i=0;i<vs.length;i++){
        if(vs[i].indexOf('=') != -1){
            var k = vs[i].split('=');
            eval('o.'+k[0]+'="'+k[1]+'"');
        }
    }
    return o;
}

function delete_reply_notify(id){
    if(!delete_reply_notify.id){
        delete_reply_notify.id=id
        show_dialog($("#confirm_delete").html())
        $('#overlay').css('z-index',100); //workaround for ff2 bug
    }
    return false;
};

function close_delete(is_delete){
    if(is_delete){
        var id=delete_reply_notify.id;
        $.get("/j/remove_notify?id="+id)
        $("#reply_notify_"+id).fadeOut();
    }
    delete_reply_notify.id=null
    close_dialog()
}

function moreurl(self, dict){
    var href = self.href, more = [];
    for (var i in dict) more.push(i + '=' + dict[i]);
    self.href += (href.indexOf('?') == -1 ? '?':'&')+ more.join('&');
}

function tip_win(e){
    $(e).next(".blocktip").show().blur_hide();
}

tip_win.hide=function(e){
    $(e).parents(".blocktip").hide()
}

function js_parser(htm){
    var tag="script>",begin="<"+tag,end="</"+tag,pos=pos_pre=0,result=script="";
    while(
        (pos=htm.indexOf(begin,pos))+1
    ){
        result+=htm.substring(pos_pre,pos);
        pos+=8;
        pos_pre=htm.indexOf(end,pos);
        if(pos_pre<0){
            break;
        }
        script+=htm.substring(pos,pos_pre)+";";
        pos_pre+=9;
    }
    result+=htm.substring(pos_pre,htm.length);

    return {
        htm:result,
        js:function(){eval(script)}
    };
}


function center(elem){
    return {
        left:(document.documentElement.offsetWidth-elem.offsetWidth)/2+'px',
        top:(document.documentElement.clientHeight-elem.offsetHeight)*.45+'px'
    }
}

function pop_win(htm,hide_close){
    if(!window.__pop_win){
        var pop_win_bg=document.createElement("div");
        pop_win_bg.className="pop_win_bg"
        document.body.appendChild(pop_win_bg)
        var pop_win_body=document.createElement("div");
        pop_win_body.className="pop_win";
        document.body.appendChild(pop_win_body)
        __pop_win={
            bg:pop_win_bg,body:pop_win_body,
            body_j:$(pop_win_body),bg_j:$(pop_win_bg)
        };
    }
    var b=__pop_win.body,body_j=__pop_win.body_j,dom=js_parser(htm);
    
    if(hide_close!==true)dom.htm='<a onclick="pop_win.close()" href="javascript:;" class="pop_win_close">x</a>'+dom.htm;
    b.innerHTML=dom.htm;

    body_j.css({display:"block"}).css(center(b)).css({visibility:"visible",zIndex:101});
    dom.js();
    pop_win.fit();
    
    if(!window.XMLHttpRequest){
        __pop_win.bg.style.top=""
    }
}

pop_win.fit=function(){
if(window.__pop_win){
    var b=__pop_win.body;
    __pop_win.bg_j.css({
        height:b.offsetHeight+20+"px",
        width:b.offsetWidth+20+"px",
        left:b.offsetLeft-10+"px",
        top:b.offsetTop-10+"px",
        zIndex:100
    }).show()
    }
}

pop_win.close=function(){
    __pop_win.bg.style.display="none";
    __pop_win.body.innerHTML="";
    __pop_win.body.style.display="none";
}

pop_win.load=function(url,cache){
    pop_win("加载中,请稍等...")
    $.ajax({url:url,success:pop_win,cache:cache||false})
    return false
}

function event_init_tab() {
    $('#tongcheng_tab').click(function() {
        if($('#tongcheng_tab_block').is(':hidden')) {
            show_tongcheng_tab();
            $().click(function() {
                hide_tongcheng_tab();
                $().unbind("click",arguments.callee);
            });
        } else {
            hide_tongcheng_tab();
        }
        return false
    })
}

function show_tongcheng_tab() {
    $('#tongcheng_tab_block').show();
    $('#tongcheng_tab span').addClass('up')
}

function hide_tongcheng_tab() {
    $('#tongcheng_tab_block').hide();
    $('#tongcheng_tab span').removeClass('up')
}

__load_bk=$.fn.load;
$.fn.load_withck = function( url, data, callback ) {
    if ($.isFunction(data)) {
        callback = data;
        data = {};
    }
    return __load_bk.call(this,url,$.extend(data,{ck:get_cookie('ck')}),callback);
}

})(jQuery);
